// Package article
// Created by GoLand
// @User: lenora
// @Date: 2024/7/12
// @Time: 17:29

package events

import (
	"camp/microbook/interactive/repository"
	"camp/microbook/pkg/logger"
	"camp/microbook/pkg/saramax"
	"context"
	"github.com/IBM/sarama"
	"time"
)

const (
	topic = "article_read"
	biz   = "article"
)

type ReadEvent struct {
	UserId    uint64 `json:"user_id"`
	ArticleId uint64 `json:"article_id"`
}

type InteractiveReadConsumer struct {
	client sarama.Client
	l      logger.Logger
	repo   repository.InteractiveRepository
}

func NewInteractiveReadConsumer(client sarama.Client, l logger.Logger, repo repository.InteractiveRepository) *InteractiveReadConsumer {
	return &InteractiveReadConsumer{client: client, l: l, repo: repo}
}

func (c *InteractiveReadConsumer) Start() error {
	group, err := sarama.NewConsumerGroupFromClient("camp-article", c.client)
	if err != nil {
		return err
	}
	go func() {
		err = group.Consume(context.Background(), []string{topic}, saramax.NewHandler[ReadEvent](c.Handle, c.l))
		if err != nil {
			c.l.Error("consumer start error", logger.Error(err))
		}
	}()
	return err
}

func (c *InteractiveReadConsumer) Handle(message *sarama.ConsumerMessage, data ReadEvent) error {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	err := c.repo.IncrReadCnt(ctx, biz, data.ArticleId)
	if err != nil {
		c.l.Error("handle article readCnt failed",
			logger.Error(err),
			logger.Uint64("article id", data.ArticleId),
		)
	}
	return err
}

type Consumer interface {
	Start() error
}
